package yushuman.rbac.service.impl;

import yushuman.rbac.dao.IBaseDao;
import yushuman.rbac.domain.dto.BaseDto;
import yushuman.rbac.domain.entity.BaseEntity;
import yushuman.rbac.domain.vo.BaseVo;
import yushuman.rbac.domain.vo.Result;
import yushuman.rbac.service.IBaseService;

import java.util.List;

/**
 * 业务层基类
 *
 * @author 俞舒熳
 * @since 2025/6/5 22:49
 */
abstract class BaseService<
        Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo extends BaseVo,
        Dao extends IBaseDao<Entity>> implements IBaseService<Entity, Dto> {

    Dao dao;

    Vo[] temp;

    @Override
    public boolean existsById(int id) {
        return dao.existsById(id);
    }

    @Override
    public Entity findById(int id) {
        return dao.findById(id);
    }

    abstract Vo convertToVo(Entity entity);

    @Override
    public Result list() {
        List<Vo> list = dao.list().stream().map(this::convertToVo).toList();
        return Result.success("查询成功", list.toArray(temp));
    }

    abstract Entity createEntity(Dto dto);

    @Override
    public Result create(Dto dto) {
        Entity entity = createEntity(dto);
        dao.save(entity);
        return Result.success("创建成功", null);
    }

    abstract void updateEntity(Dto dto, Entity entity);

    @Override
    public Result update(Dto dto, int id) {
        if (!existsById(id)) {
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity = dao.findById(id);
        updateEntity(dto, entity);
        dao.save(entity);
        return Result.success("更新成功", null);
    }
}
